#!/usr/bin/perl
#
# emailmove - copy the email info from the "email" field of the
# user and person record into the "email" table
#
use Counter;

$fromkey = shift;


$users = Counter::open(O_RDWR);
if ($fromkey ne "old") {
    while ($key = $users->each()) {
	++ $count;
	print STDERR "$count\r" if $count % 100 == 0 && -t STDERR;
	next if $fromkey && $key < $fromkey;
	$rec = $users->get($key);
	if (!$$rec{email}) {
	    warn "No email in $key\n";
	    next;
	}
	if (!$rec->hasemail($rec->{email})) {
	    trytoadd($rec, $rec->{email}, "main");
	}
	$pers = $rec->person();
	if ($pers && $pers->{email}) {
	    $m2 = $pers->{email};
	    if ($m2 =~ /@/ && !$rec->hasemail($m2)) {
		trytoadd($rec, $m2, "public");
	    }
	}
    }
}

# Try to add old emails
my $line = 0;
open(DATA, "db/users.txt");
while (<DATA>) {
    ++ $line;
    print STDERR "L$line\r" if $line % 100 == 0 && -t STDERR;
    chop;
    if (/^\/\/(\d+)$/) {
	$key = $1;
	undef $mail;
    } elsif (/^email:/) {
	$mail = $';
	$rec = $users->get($key);
	next if !$rec;
	if ($mail && $mail =~ /@/ && !$rec->hasemail($mail)) {
	    trytoadd($rec, $mail, "old");
	}
    }
}

sub trytoadd {
    my $rec = shift;
    my $mail = shift;
    my $class = shift;

    eval '$rec->addemail($mail, $class)';
    if ($@) {
	warn $@;
    } else {
	print $rec->key, ": $class $mail\n";
    }
}


